import express from 'express'
import mysql from 'mysql2/promise'
import { dbConfig } from '../config/database.js'

const router = express.Router()

// 获取比赛的所有玩家
router.get('/:match_id', async (req, res) => {
  try {
    const { match_id } = req.params
    const connection = await mysql.createConnection(dbConfig)
    const [rows] = await connection.query(
      'SELECT p.* FROM players p JOIN match_players mp ON p.id = mp.player_id WHERE mp.match_id = ?',
      [match_id]
    )
    await connection.end()
    res.json(rows)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

// 添加玩家到比赛
router.post('/', async (req, res) => {
  try {
    const { match_id, player_id } = req.body
    const connection = await mysql.createConnection(dbConfig)
    const [result] = await connection.query(
      'INSERT INTO match_players (match_id, player_id) VALUES (?, ?)',
      [match_id, player_id]
    )
    await connection.end()
    res.json({ id: result.insertId })
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

export default router 